#nullable enable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PHMEE.CommonUtils;
using PHMEE.DTOS.Diagnosis;
using PHMEE.EnergyEfficiency;
using PHMEE.Entities.DaqInfo.Ams;
using PHMEE.IServices.Diagnosis;
using Volo.Abp.Domain.Repositories;

namespace PHMEE.Services.Diagnosis;

public class AmsDigitalAppService : PHMEEAppService, IAmsDigitalAppService
{
    private readonly IReadOnlyRepository<DigitalConfig, Guid> _digitalConfigRepository;
    private readonly IDigitalTDRepository _digitalTDRepository;
    private readonly IPHMEETimeProvider _phmeeTimeProvider;

    public AmsDigitalAppService(
        IReadOnlyRepository<DigitalConfig, Guid> digitalConfigRepository,
        IDigitalTDRepository digitalTDRepository, 
        IPHMEETimeProvider phmeeTimeProvider)
    {
        _digitalConfigRepository = digitalConfigRepository;
        _digitalTDRepository = digitalTDRepository;
        _phmeeTimeProvider = phmeeTimeProvider;
    }
    
    /// <summary>
    /// 根据 VesselId 和 UnitId 获取该 Unit 的所有 AMS digital 实时值
    /// </summary>
    /// <param name="vesselId"></param>
    /// <param name="unitId"></param>
    /// <returns></returns>
    public async Task<IEnumerable<DigitalLatestDto>> GetLatestDigitalValuesAsync(Guid vesselId, Guid unitId)
    {
        var utcNow = _phmeeTimeProvider.GetUtcNow();
        
        var digitalConfigs = await _digitalConfigRepository.GetListAsync(x => x.VesselId == vesselId && x.UnitId == unitId);
        var tagNames = digitalConfigs.Select(x => x.TagName).ToList();
        
        var digitalRecords = await _digitalTDRepository.GetLatestRecordBeforeDateTimeByTagNamesAsync(vesselId, utcNow, tagNames);
        
        return digitalRecords.Select(x => new DigitalLatestDto
        {
            TagName = x.TagName,
            TagDesc = x.TagDesc,
            V = x.V,
        }).OrderBy(x => x.TagName);
    }
}